package cn.com.dcsgo.exception;

import cn.com.dcsgo.common.Result;
import cn.com.dcsgo.enums.ResultEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * GlobalExceptionHandler
 *
 * @author Dcsgo
 * @since 20/5/2025 下午 4:23
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理其他未定义的异常
     */
    @ExceptionHandler({Throwable.class})
    public Result<String> throwableHandler(Throwable t) {
        log.error("throwableHandler:", t);
        String errorMsg = t.getMessage();
        if (!StringUtils.hasText(errorMsg)) {
            return new Result<>(ResultEnums.ERROR.getCode(), "操作失败，请联系管理人员");
        }
        return new Result<>(ResultEnums.ERROR.getCode(), errorMsg);
    }

    /**
     * 参数效验异常处理
     */
    @ExceptionHandler({BindException.class})
    public Result<String> bindException(BindException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        StringBuilder errors = new StringBuilder();
        for (ObjectError allError :
                allErrors) {
            errors.append(allError.getDefaultMessage()).append(",");
        }
        //移除最后多余的逗号
        errors.delete(errors.length() - 1, errors.length());
        String errorInfo = errors.toString();
        log.error("bindException:{}", errorInfo);
        return new Result<>(ResultEnums.PARAMS_ERROR.getCode(), errorInfo);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler({BusinessException.class})
    public Result<String> businessException(BusinessException e) {
        log.error("businessException:{}", e.getMessage());
        return new Result<>(e.getErrCode(), e.getMessage());
    }
}
